﻿using AdventureWorks.DataAccess.repository;
using System.Collections.Generic;
using AdventureWorks.DataAccess.SearchCriterias;
using AdventureWorks.Domain;
using AdventureWorks.DataAccess.Utils;
using NHibernate;
using System.Linq;
namespace AdventureWorks.DataAccess.Task
{
    public class ProductInventoryTask : TaskBase<IProductInventoryRepository, ProductInventoryRepository>
    {
        public ProductInventoryTask() : base() { }
        public ProductInventoryTask(IProductInventoryRepository repo, ISessionFactory factory) : base(repo, factory) { }

        public IEnumerable<ProductInventory> GetProductInventoryByLocation(ProductInventorySearchCriteria searchCriteria)
        {
            using (var session = Factory.OpenSession())
            {
                return Repository.GetProductInventory(session, searchCriteria).Paging(searchCriteria);
            }
        }

        public IEnumerable<ProductInventory> GetProductInventoryTotal(ProductInventorySearchCriteria searchCriteria)
        {
            using (var session = Factory.OpenSession())
            {
                var result = Repository.GetProductInventory(session, searchCriteria)
                    .GroupBy(m => m.Product)
                    .Select(g => new ProductInventory { Product =  g.Key , Quantity = g.Sum(x => x.Quantity) });
                return result;
            }
        }
    }
}
